package com.cf.base.http.generator.impl;

import com.alibaba.fastjson.JSONException;
import com.cf.base.http.core.RetrofitService;
import com.cf.base.http.generator.IErrorAdapter;
import com.cf.base.http.bean.ErrorResponse;
import com.cf.base.http.utils.Utils;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.UnknownHostException;

import retrofit2.HttpException;
import retrofit2.Response;

/**
 * 未完成- 返回的成功失败 需要跟接口一致，保证统一性（不过对后台要求过高）
 *
 * @author yangji
 */
public class DefaultErrorAdapter implements IErrorAdapter {

    @Override
    public <T> T call(RetrofitService bean, Method method, Throwable throwable) {
        Type returnType = Utils.getReturnType(method);
        Type observableType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
        Class cls = Utils.getRawType(observableType);
        return (T) getErrorBody(cls, throwable);
    }

    private <T extends ErrorResponse> T getErrorBody(Class<T> tClass, Throwable throwable) {
        T baseInfo = null;
        try {
            baseInfo = tClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        int code;
        String message;

        System.err.println(throwable.getMessage() + " " + throwable.getClass());

        if (throwable instanceof UnknownHostException) {
            System.err.println("域名解析错误");
            //域名解析失败
        }

        //如果设置的
        // 第三方网站 网络异常
        // CF connectTimeout、readTimeout、writeTimeout 时间太短有可能出现是网络异常
        if (throwable instanceof ConnectException) {
            System.err.println("网络连接异常");
        }

        if (throwable instanceof java.io.InterruptedIOException) {
            System.err.println("网络 callTimeout 超时");
        }
        if (throwable instanceof java.net.SocketTimeoutException) {
            System.err.println("网络 connectTimeout/readTimeout 超时");
        }
        if (throwable instanceof java.lang.IllegalArgumentException) {
            System.err.println("网络配置时间太少");
        }
        ////解析
        if (throwable instanceof JSONException) {
            System.err.println("fastJson 解析异常");
        }

        if (throwable instanceof org.json.JSONException) {
            System.err.println("org.json 解析异常");
        }

        if (throwable instanceof com.google.gson.stream.MalformedJsonException) {
            System.err.println("Gson 解析异常");
        }

        if (throwable instanceof HttpException) {
            HttpException error = (HttpException) throwable;
            Response res = error.response();
            if (res != null) {
                code = res.code();
                baseInfo.setCode(code);
                baseInfo.setMessage("http code" + code);
            }
        }
        return baseInfo;
    }
}
